<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="cpAnchorList"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">基础信息</div>
          <customFormItem
            label="类型"
            name="busType" :parent="_self" :form="form"
            :type="constCommon.formItemType.selectStatic.name"
            :config="{options: busTypeSource}"
            :disabled="!propParent.cpFormNew"
            :clearable="false"
            help="将根据该类型筛选待结算数据，保存后不可修改"
          />
          <customFormItem
            label="会计期间"
            name="period" :parent="_self" :form="form"
            :type="constCommon.formItemType.selectStatic.name"
            :config="{options: periodList, label: 'period',labelShow: 'periodShow', value: 'period'}"
            :disabled="!propParent.cpFormNew"
            :clearable="false"
            help="将根据会计区间筛选待结算数据，保存后不可修改"
            @change="periodChange"
          />
          <div class="label-date"><strong>结算期间</strong>
            {{form.startDate ? form.startDate + ' ~ ' + form.endDate : ''}}
          </div>
          <customFormItem label="结算金额" name="amount" :parent="_self" :form="form" disabled />
          <customFormItem label="备注" name="remark" :parent="_self" :form="form" />
        </template>
      </customForm>

      <div id="box-wait" class="box-title" v-show="!propReadonly">待结算<small style="padding-left: 10px;font-size: 14px; line-height: 0px; color: #ec9006;">{{settlementType}}</small></div>
      <data-view
        v-show="!propReadonly"
        propViewKey="finance_item_add_await"
        :propPageSize="500"
        :propInitData="form"
        :propSubHeight="winHeight/2"
        ref="childBillItemAll"
        :propAutoFetchData="false"
        :propHideFlowSelect="true"
        :propFlowKey="propParent.propFlowKey"
        :propShowToolBar="true"
        @extra-button-click="extraButtonClick"
        :propIsTdesign="true"
        :propTableHide="propParent.cpFormNew"
        propTableHideMsg="请先保存主单据再操作"
        :propHeight="winHeight/2"
      />

      <div id="box-dtl" class="box-title">已结算</div>
      <data-view
        propViewKey="finance_bill_item"
        :propPageSize="500"
        :propInitData="form"
        ref="childBillItemSelf"
        :propHeight="winHeight/2"
        :propAutoFetchData="false"
        :propHideFlowSelect="true"
        :propShowToolBar="true"
        :propOnlyQueryAll="propReadonly"
        :propFlowKey="propParent.propFlowKey"
        @extra-button-click="extraButtonClick"
        :propTableHide="propParent.cpFormNew"
        propTableHideMsg="请先保存主单据再操作"
        :propIsTdesign="true"
      />
    </div>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {
        startDate: null,
        endDate: null,
        period: null,
        periodId: null
      },
      viewData: {},
      dataFormat: 'yyyy年MM月dd日',
      operateFlag: [1, -1], //1:添加 -1删除
      settlementType: null,  //
      busTypeSource: [{
        value: 0,
        label: '非一物一码'
      },
      {
        value: 1,
        label: '一物一码'
      },
      {
        value: 2,
        label: '全部'
      }],
      systemSettlementField: null,  //结算依据字段,
      systemSettlementFlowValue: 'end',  //结算依据字段,
      winHeight: window.innerHeight,

      // 会计期间列表
      periodList: []
    }
  },
  created() {
    this.systemSettlementField = this.parameters.systemSettlementField()
    this.systemSettlementFlowValue = this.parameters.systemSettlementFlowValue()
    if (this.systemSettlementField === 'flowStatus') {
      this.settlementType = '(审核日期在该会计区间内的消耗清单)'
    } else if (this.systemSettlementField === 'accountCheckStatus') {
      this.settlementType = '(扎账日期在该会计区间内的消耗清单)'
    } else {
      global.utilMessage.alertFail('未设置有效系统参数【结算单数据筛选字段】，请联系运营进行设置后再进行结算操作!', '系统参数缺失提醒', {
        confirmButtonText: '确定',
        type: 'warning',
        callback: action => {
          this.propParent.setViewFormVisible(false)
        }
      })
      return
    }

    this.getPeriodList()

    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        this.fetchData()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      afterClick(button, data) {
        let {key: buttonKey} = button
        if (buttonKey == 'cp_send_mscm') {
          that.utilVue.loadShow(true)
          that.$ajax.post('/finance/settlement/syncMSCM', that.form).then(resp => {
            that.utilVue.loadHide()
            that.utilMessage.success('推送成功')
            this.fetchData()
          })
        } else if (buttonKey == 'cp_export_mscm') {
          that.utilVue.loadShow(true)
          that.$ajax.post('/finance/settlement/getDataForMSCM', that.form).then(resp => {
            if (resp.success) {
              global.utils.downloadContextRes(resp.data)
              that.utilVue.loadHide()
              that.utilMessage.success('导出成功')
              this.fetchData()
            }
          })
        }
      }
    })
  },
  methods: {
    //查询可结算的帐单
    fetchData() {
      if (this.$refs.childBillItemAll) {
        this.$refs.childBillItemAll.setQueryWrapper(this.fetchQueryWrapperAll())
      }

      this.$refs.childBillItemSelf.setQueryWrapper(this.fetchQueryWrapperSelf())
    },
    //所有本周期内未结算的记帐单
    fetchQueryWrapperAll() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('settlementId', 0)
          .eq('flagSupplier', 1)
          .between('flowModified', [this.form.startDate, this.form.endDate])
        if (this.form.busType == 0) {
          queryWrapper.eq('flagOmoc', 0)
        }
        if (this.form.busType == 1) {
          queryWrapper.eq('flagOmoc', 1)
        }
      } else {
        queryWrapper.ne(1, 1)
      }

      //筛选结算单依据字段
      queryWrapper.eq(this.systemSettlementField, this.systemSettlementFlowValue)
      return queryWrapper
    },
    //本结算单的记帐单
    fetchQueryWrapperSelf() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('settlementId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      return queryWrapper
    },
    //保存结算单Id
    saveBillSettlement(billItemIds, operateFlag) {
      let parameter = {billItemIds, settlementId: this.form.id, operateFlag}

      this.utilVue.loadShow(true)
      this.$ajax.post('/finance/bill_item/saveSettlement', parameter).then(resp => {
        this.utilVue.loadHide()
        this.fetchData()
        this.refreshRefs()
      })
    },
    //一次保存所有结算
    async saveBillAllSettlement() {
      let parameter = {
        settlementId: this.form.id,
        busType: this.form.busType,
        startDate: this.dates.toDate(this.form.startDate, 'yyyy-MM-dd'),
        endDate: this.dates.toDate(this.form.endDate, 'yyyy-MM-dd'),
        queryString: this.$refs.childBillItemAll.generateQuery()
      }

      let itemsMap = {}
      this.$refs.childBillItemAll.tableForm.items.forEach(item => {
        itemsMap[item.field] = item
      })
      let data = this.$refs.childBillItemAll.tableForm.data
      let msg = '是否添加全部待记账单明细？'
      let msgArr = []
      Object.keys(data).forEach(key => {
        if (this.strings.isNotBlank(data[key])) {
          msgArr.push(itemsMap[key].title + ':' + data[key])
        }
      })
      if (msgArr.length > 0) msg = '是否添加 【' + msgArr.join(',') + '】 的全部待记账单明细？'

      const result = await this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
      })
      if (result) {
        console.log('parameter', parameter)
        console.log('this.$refs.childBillItemAll', this.$refs.childBillItemAll)
        this.utilVue.loadShow(true)
        this.$ajax.post('/finance/bill_item/saveAllSettlement', parameter).then(resp => {
          this.utilVue.loadHide()
          if (resp.code == 0) {
            this.fetchData()
            this.refreshRefs()
          }
        })
      }
    },
    deleteBillAllSettlement(billItemIds, operateFlag) {
      let parameter = {billItemIds, settlementId: this.form.id, operateFlag}
      this.utilVue.loadShow(true)
      this.$ajax.post('/finance/bill_item/deleteBillAllSettlement', parameter).then(resp => {
        this.utilVue.loadHide()
        this.fetchData()
        this.refreshRefs()
      })
    },
    /**刷新上级网格和本页面表单
       *
       */
    refreshRefs() {
      //刷新本页面表单
      this.propParent.ocRefreshCurrentRow()
      //刷新上级网格明细
      this.propParent.ocRefresh()
    },

    extraButtonClick({button, data, index}) {
      let {key: buttonKey} = button
      if (buttonKey.indexOf('cp') == 0) { //客户端操作
        let billItemIds = []
        let operateIndex = 0
        if (data instanceof Array) {
          if (data.length == 0) {
            this.utilMessage.warning('请先选择需要结算的记账单明细')
            return false
          }
          billItemIds = data.map(d => d.id)
          operateIndex = data[0].settlementId > 0 ? 1 : 0 //有结算单就删除，没有则添加
        } else {
          billItemIds = [data.id]
          operateIndex = data.settlementId > 0 ? 1 : 0
        }
        this.saveBillSettlement(billItemIds, this.operateFlag[operateIndex])
      }
      if (buttonKey == 'all_save') {
        if (this.form.flowStatus && this.form.flowStatus != 'start') {
          this.utilMessage.warning('制单状态下才添加全部')
          return false
        }
        this.saveBillAllSettlement()
      }
      if (buttonKey == 'multiple_delete') {
        let billItemIds = []
        if (this.form.flowStatus && this.form.flowStatus != 'start') {
          this.utilMessage.warning('制单状态下才可以删除')
          return false
        }
        if (data instanceof Array) {
          if (data.length == 0) {
            this.utilMessage.warning('请先选择需要结算的记账单明细')
            return false
          }
          billItemIds = data.map(d => d.id)
        }
        this.utilMessage.confirm('确定移除所添加的账单么', () => {
          this.deleteBillAllSettlement(billItemIds, -1)
        })
      }
    },

    // 获取会计期间列表
    getPeriodList() {
      let wrapper = this.$newWrapper()
      wrapper.orderConditions.push({ field: 'gmtCreate', rule: 'desc' })
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
        orderString: JSON.stringify(wrapper.orderConditions)
      }
      this.$ajax.get('/finance/period/list', {params}).then(resp => {
        console.log('resp', resp)
        if (resp.data) {
          resp.data.forEach(item => {
            item.periodShow = `<strong style="display: inline-block;width: 80px;">${item.period}</strong><small>(${item.startDate}--${item.endDate})</small>`
          })
          this.periodList = resp.data
        }
      })
    },

    // 会计区间改变后
    periodChange(value, item) {
      this.$set(this.form , 'startDate', item.startDate)
      this.$set(this.form , 'endDate', item.endDate)
      this.$set(this.form , 'periodId', item.id)
      this.$set(this.form , 'period', item.period)
      this.fetchData()
    }

  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {customAnchor},
  computed: {
    // 导航列表
    cpAnchorList() {
      if (this.propReadonly) {
        return [
          { name: 'box-base', title: '基础信息' },
          { name: 'box-dtl', title: '已结算' },
        ]
      }
      return [
        { name: 'box-base', title: '基础信息' },
        { name: 'box-wait', title: '待结算' },
        { name: 'box-dtl', title: '已结算' },
      ]
    }

  },
  watch: {
    'form.period': {
      handler(newVal) {
        // this.changePeriod(newVal)
      },
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
  .label-date {
    display: inline-block;
    min-width: 320px;
    strong {
      display: inline-block;
      width: 120px;
      font-weight: 700;
      text-align: right;
      padding-right: 10px !important;
    }
  }
</style>
